package com.py.pythink.service.impl;

import com.alibaba.fastjson.JSON;
import com.py.pythink.bo.UserBo;
import com.py.pythink.config.RedisKeyConfig;
import com.py.pythink.config.SystemConfig;
import com.py.pythink.dao.UserDao;
import com.py.pythink.dao.UserDetailDao;
import com.py.pythink.dao.UserLogDao;
import com.py.pythink.entity.User;
import com.py.pythink.entity.UserDetail;
import com.py.pythink.entity.UserLog;
import com.py.pythink.service.intf.UserService;
import com.py.pythink.third.JedisUtil;
import com.py.pythink.third.JwtUtil;
import com.py.pythink.util.EncryptUtil;
import com.py.pythink.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao dao;
    @Autowired
    private UserLogDao userLogDao;
    @Autowired
    private UserDetailDao detailDao;
    @Value("${idler.rsa.pri}")
    private String priKey;
    @Override
    public R checkPhone(String phone) {
       if(dao.selectByPhone(phone)!=null){
           User user = dao.selectByPhone(phone);
           if(user.getFlag()==SystemConfig.USER_OK){
               return R.fail("额滴乖乖，手机号已经存在，可以去尝试登陆哦！");
           }else{
               return R.fail("完犊子的，手机号异常，联系客服");
           }
       }else{
           return R.ok();
       }
    }

    @Override
    @Transactional//启用事务
    public R register(UserBo userBo, String ip) {
       //1.校验-手机号的可用性
        if(checkPhone(userBo.getPhone()).getCode()==SystemConfig.R_OK){
            //2.校检-手机号验证码
            if(!JedisUtil.checkKey(RedisKeyConfig.CODE_R+userBo.getPhone())){
                //3.进行密码的脱敏
                User user = new User(userBo.getPhone(), EncryptUtil.rsaEnc(priKey,userBo.getPass()),SystemConfig.USER_OK);
                //4.注册账号
                if(dao.insert(user)>0){
                    //5.可设置新人有礼
                    userLogDao.insert(new UserLog(SystemConfig.USER_REGISTER,"注册",ip,user.getId(),new Date()));
                    //初始化用户详情表
                    detailDao.insert(new UserDetail(user.getId(),new Date()));
                    return  R.ok();
                }

            }
        }
        return R.fail("该手机已经存在");
    }

    @Override
    public R login(UserBo userBo,String ip) {
        //令牌，前后端分离项目。调用接口的，可以是PC网站、手机网站、APP、小程序、智能硬件，不使用Session
        //1.查询数据库
        User user = dao.selectByPhone(userBo.getPhone());
        if(user!=null && user.getFlag()==SystemConfig.USER_OK){
            //验证密码
            if(user.getPass().equals(EncryptUtil.rsaEnc(priKey,userBo.getPass()))){
                if(!JedisUtil.checkKey(RedisKeyConfig.USER_TOKEN_PHONE+userBo.getPhone())){
                    //登陆成功，生成令牌
                    String token = JwtUtil.createJwt(userBo.getPhone());
                    //存储令牌
                    JedisUtil.addStr(RedisKeyConfig.USER_TOKEN_PHONE+userBo.getPhone(),token,RedisKeyConfig.USER_TOKEN_TIME);
                    JedisUtil.addStr(RedisKeyConfig.USER_TOKEN+token, JSON.toJSONString(user),RedisKeyConfig.USER_TOKEN_TIME);
                    userLogDao.insert(new UserLog(SystemConfig.USER_LOGIN,"账号密码登陆",ip,user.getId(),new Date()));
                    return R.ok(token);
                }else{
                    return R.fail("亲,你在其他地方登陆！");
                }

            } return R.fail("账号或者密码错误");

        }return R.fail("账号不存在 或者输入有误");

    }
    //短信验证登录
    @Override
    public R loginCode(UserBo userBo, String ip) {
        User user = dao.selectByPhone(userBo.getPhone());
        if(user!=null && user.getFlag()==SystemConfig.USER_OK){
            if(!JedisUtil.checkKey(RedisKeyConfig.USER_TOKEN_PHONE+userBo.getPhone())){//判断是否已经登陆
                if(JedisUtil.checkKey(RedisKeyConfig.CODE_L+userBo.getPhone())){
                    if(userBo.getCode().equals(Integer.parseInt(JedisUtil.getStr(RedisKeyConfig.CODE_L+userBo.getPhone())))){//验证验证码
                        //登陆成功 生成令牌
                        String token = JwtUtil.createJwt(userBo.getPhone());
                        JedisUtil.addStr(RedisKeyConfig.USER_TOKEN_PHONE+userBo.getPhone(),token,RedisKeyConfig.USER_TOKEN_TIME);
                        JedisUtil.addStr(RedisKeyConfig.USER_TOKEN+token, JSON.toJSONString(user),RedisKeyConfig.USER_TOKEN_TIME);
                        userLogDao.insert(new UserLog(SystemConfig.USER_LOGIN,"短信验证登陆","ip",user.getId(),new Date()));
                        return R.ok(token);

                    }
                }

            }else{
                return R.fail("你已经登陆过了");
            }

        }
        return R.fail("账号或者验证码错误");
    }

    @Override
    public R loginOut(String token,String ip) {
        System.err.println(token+"前端");
        if(JedisUtil.checkKey(RedisKeyConfig.USER_TOKEN+token)){
            User user = JSON.parseObject(JedisUtil.getStr(RedisKeyConfig.USER_TOKEN + token), User.class);
            JedisUtil.delStr(RedisKeyConfig.USER_TOKEN_PHONE+user.getPhone());
            System.err.println(JedisUtil.delStr(RedisKeyConfig.USER_TOKEN_PHONE+user.getPhone()));
            JedisUtil.delStr(RedisKeyConfig.USER_TOKEN+token);
            userLogDao.insert(new UserLog(SystemConfig.USER_LOGINOUT,"退出登陆",ip,user.getId(),new Date()));
            return R.ok();
        }
        System.out.println("退出登陆失败"+R.fail("dada").getCode());
        return R.fail("退出登陆失败");
    }

    @Override
    public R checkToken(String token) {
        if(JedisUtil.checkKey(RedisKeyConfig.USER_TOKEN+token)){
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R findPass(String phone,String ip) {
        User user = dao.selectByPhone(phone);
        if(user!=null && user.getFlag()==SystemConfig.USER_OK){
            if(!JedisUtil.checkKey(RedisKeyConfig.CODE_F+phone)){//主要用来判断验证码
                userLogDao.insert(new UserLog(SystemConfig.USER_FIND,"找回密码",ip,user.getId(),new Date()));
                return  R.ok();
            }
        }
            return R.fail("亲，你的手机号输入有误哦！");

    }



}
